package main

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
)

func Auth(ctx *gin.Context) {
	if uid:=getUidFromHeader(ctx); uid!=""{
		ctx.Set("uid", uid)
		ctx.Next()
	} else {
		ctx.String(http.StatusForbidden, "身份校验失败，请重新登录")
		ctx.Abort()
	}
}


func getUidFromHeader(ctx *gin.Context) string {
	if token:=strings.TrimSpace(ctx.Request.Header.Get("jwt-token")); token!=""{
		_, payload, err:=VerifyJWT(token, JWT_SECRET)
		if err!=nil{
			return ""
		}
		if uid, exists:=payload.UserDefined["uid"]; exists {
			return uid.(string)
		}
	}
	return ""
}